public class LeetCode {
    //493. 翻转对
    int[] tmp;
    int ret = 0;

    public int reversePairs(int[] nums) {
        tmp = new int[nums.length];
        mergeSort(nums,0,nums.length-1);
        return ret;
    }
    //降序
    public void mergeSort(int[] nums,int left,int right){
        if(left>=right){
            return;
        }
        //中间节点
        int mid = (left+right)/2;
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);
        //判断
        int cur1 = left,cur2 = mid+1;
        while(cur1<=mid){
            while(cur2<=right&&nums[cur2]>=nums[cur1]/2.0){
                cur2++;
            }
            if(cur2>right)
                break;
            ret+=right-cur2+1;
            cur1++;
        }
        cur1 = left;
        cur2 = mid+1;
        int i = left;
        while(cur1<=mid && cur2<=right){
            tmp[i++] = nums[cur1]>=nums[cur2]?nums[cur1++]:nums[cur2++];
        }
        while(cur1<=mid){
            tmp[i++] = nums[cur1++];
        }
        while(cur2<=right){
            tmp[i++] = nums[cur2++];
        }
        for (int j = left; j <= right; j++) {
            nums[j] = tmp[j];
        }
    }
    //升序
    public void mergeSort2(int[] nums,int left,int right){
        if(left>=right){
            return;
        }
        //中间节点
        int mid = (left+right)/2;
        mergeSort2(nums,left,mid);
        mergeSort2(nums,mid+1,right);
        //判断
        int cur1 = left,cur2 = mid+1;
        while(cur2<=right){
            while(cur1<=mid&&nums[cur2]>=nums[cur1]/2.0){
                cur1++;
            }
            if(cur1>mid)
                break;
            ret+=mid-cur1+1;
            cur2++;
        }
        cur1 = left;
        cur2 = mid+1;
        int i = left;
        while(cur1<=mid && cur2<=right){
            tmp[i++] = nums[cur1]<=nums[cur2]?nums[cur1++]:nums[cur2++];
        }
        while(cur1<=mid){
            tmp[i++] = nums[cur1++];
        }
        while(cur2<=right){
            tmp[i++] = nums[cur2++];
        }
        for (int j = left; j <= right; j++) {
            nums[j] = tmp[j];
        }
    }
}
